package com.league.zjxn.app

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.league.zjxn.entity.UserInfo
import kotlin.reflect.KProperty

object SPSConstance {

    var token by APreference(name = "token", String::class.java)

    var userInfo by APreference(name = "userInfo", UserInfo::class.java)

}

@Suppress("UNCHECKED_CAST")
class APreference<T>(var name: String, var type: Class<T>) {

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T? =
        getAPreference(name, type)

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) =
        putAPreference(name, value)

    private fun putAPreference(name: String, value: T?) {


        when (value) {
            is Int -> SPStaticUtils.put(name, value)
            is Float -> SPStaticUtils.put(name, value)
            is Long -> SPStaticUtils.put(name, value)
            is Boolean -> SPStaticUtils.put(name, value)
            is String -> SPStaticUtils.put(name, value)
            else -> {
                SPStaticUtils.put(name, GsonUtils.toJson(value))
            }
        }
    }

    private fun getAPreference(name: String, type: Class<T>): T? = when {
        type.isAssignableFrom(Int::class.java) -> {
            SPStaticUtils.getInt(name, -1) as T
        }
        type.isAssignableFrom(Float::class.java) -> {
            SPStaticUtils.getFloat(name, -1F) as T
        }
        type.isAssignableFrom(Long::class.java) -> {
            SPStaticUtils.getLong(name, -1L) as T
        }
        type.isAssignableFrom(Boolean::class.java) -> {
            SPStaticUtils.getBoolean(name, false) as T
        }
        type.isAssignableFrom(String::class.java) -> {
            SPStaticUtils.getString(name, null) as? T
        }
        else -> {
            val value = SPStaticUtils.getString(name, null)
            if (value != null)
                GsonUtils.fromJson(value, type)
            else null
        }
    }
}